package com.ijolas.rhino;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;

public class URLDecoder {

	private static String function = "function B(a){var b=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";var c,d,e,f,g,h,i,j,k=0,l=0,m=\"\",n=[];if(!a){return a}a+=\"\";do{f=b.indexOf(a.charAt(k++));g=b.indexOf(a.charAt(k++));h=b.indexOf(a.charAt(k++));i=b.indexOf(a.charAt(k++));j=f<<18|g<<12|h<<6|i;c=j>>16&255;d=j>>8&255;e=j&255;if(h==64){n[l++]=String.fromCharCode(c)}else if(i==64){n[l++]=String.fromCharCode(c,d)}else{n[l++]=String.fromCharCode(c,d,e)}}while(k<a.length);m=n.join(\"\");return m}";

	public static String getDecodedURL(String encodedURL) {
		Context cx = Context.enter();
		Scriptable scope = cx.initStandardObjects();

		cx.evaluateString(scope, function, "<src>", 0, null);

		Function f = (Function) scope.get("B", scope);
		Object[] fArgs = new Object[] { encodedURL };
		Object result = f.call(cx, scope, scope, fArgs);

		String decodedURL = Context.toString(result);

		Context.exit();

		return decodedURL;
	}

}
